﻿using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.Data;
using System.Data.SqlClient;
using Facebook;
using EsaProjectRest.Service;
using System.Collections.Generic;
using System.Dynamic;


namespace EsaProjectRest.Facebook
{

    public class PostFB
    {
        public Boolean UpdateMyPostsFB(string id)
        {
            ServiceRest service1 = new ServiceRest();
            Services services = new Services();

            try
            {
                service1.OpenConnection();
                string[] date = new string[10];
                char[] split = { 'T' };
                char[] split2 = { '+' };
                char[] split3 = { '-' };
                string date_now;
                int likes;
                int comments;
                int flag = 0;
                int flag2 = 0;
                int month;
                int day;
                string accessToken = services.ReadToken(id, "Facebook");

                var client = new FacebookClient(accessToken);
                dynamic id_me = client.Get("me");
                string id_fb = id_me.id;

                dynamic me = client.Get("me/feed?fields=message,from,picture,comments,likes&limit=50");
                int month_attuale = (int)System.DateTime.Now.Month - 1;
                int day_attuale = (int)System.DateTime.Now.Day;

                while (flag2 == 0)
                {
                    for (int i = 0; i < 50; i++)
                    {
                        try
                        {
                            if ((me.data[i].message != null) && (me.data[i].from.id == id_fb))
                            {
                                string[] data = me.data[i].created_time.ToString().Split(split);
                                string date_fb = data[0];
                                string[] time_err = data[1].Split(split2);
                                string time = time_err[0];

                                string[] control_data = date_fb.Split(split3);
                                month = int.Parse(control_data[1]);
                                day = int.Parse(control_data[2]);
                                System.Diagnostics.Debug.Print("1: " + day);
                                System.Diagnostics.Debug.Print("2: " + day_attuale);
                                System.Diagnostics.Debug.Print("3: " + month);
                                System.Diagnostics.Debug.Print("4: " + month_attuale);
                                if ((day <= day_attuale && month == month_attuale + 1) || (day >= day_attuale && month == month_attuale))
                                {
                                    System.Diagnostics.Debug.Print("OK");
                                }
                                else
                                {
                                    i = 50;
                                    flag = 1;
                                    flag2 = 1;
                                }
                                date_now = date_fb + " " + time;

                                DateTime aa = Convert.ToDateTime(date_now);
                                date_now = aa.ToString();


                                string message = HttpUtility.HtmlEncode(me.data[i].message.ToString());

                                DataSet vds = new DataSet();
                                string vsql = string.Format("SELECT Id FROM [Post] WHERE (Id_user = '" + id + "') and (Message = '" + message + "') and (Date = '" + date_now + "') and (SocialNetwork = 'Facebook')");
                                SqlCommand vCom = new SqlCommand(vsql, service1.conn);
                                SqlDataAdapter vda = new SqlDataAdapter(vCom);
                                vda.Fill(vds);
                                try
                                {
                                    //memorize id
                                    string id_post = vds.Tables[0].Rows[0]["Id"].ToString();
                                    System.Diagnostics.Debug.Print("Id_post: " + id_post);
                                    vda.Dispose();

                                    likes = comments = 0;


                                    if (me.data[i].likes != null)
                                    {
                                        foreach (var name in me.data[i].likes.data)
                                            likes++;

                                    }


                                    if (me.data[i].comments != null)
                                    {
                                        foreach (var name in me.data[i].comments.data)
                                            comments++;


                                    }

                                    string sql2 = string.Format("UPDATE [Post] SET N_Likes='" + likes + "',N_Comments='" + comments + "' WHERE (Id = '" + id_post + "') ");
                                    System.Diagnostics.Debug.Print("Sql: " + sql2);
                                    SqlCommand com2 = new SqlCommand(sql2, service1.conn);
                                    com2.ExecuteNonQuery();
                                }
                                catch (Exception ex)
                                {
                                    System.Console.WriteLine(ex.Message);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Console.WriteLine(ex.Message);
                        }
                    }
                    if (flag == 0)
                    {
                        try
                        {
                            System.Diagnostics.Debug.Print("Paging");
                            string paging = me.paging.next.ToString();
                            char[] split4 = { '?' };

                            string[] next_page = paging.Split(split4);
                            me = client.Get(id_fb + "/feed?" + next_page[1]);
                        }
                        catch (Exception ex)
                        {
                            System.Console.WriteLine(ex.Message);
                            flag2 = 1;
                            System.Diagnostics.Debug.Print("Catch Paging");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }
            return true;
        }

        public static string RefreshAccessToken(string currentAccessToken)
        {
            FacebookClient fbClient = new FacebookClient();
            Dictionary<string, object> fbParams = new Dictionary<string, object>();
            fbParams["client_id"] = "336794829783831";
            fbParams["grant_type"] = "fb_exchange_token";
            fbParams["client_secret"] = "40f168abccf81155de349191b9544c8d";
            fbParams["fb_exchange_token"] = currentAccessToken;
            JsonObject publishedResponse = fbClient.Get("/oauth/access_token", fbParams) as JsonObject;
            return publishedResponse["access_token"].ToString();
        }


        public Boolean MyPostsFB(string id)
        {
            ServiceRest service1 = new ServiceRest();
            Services services = new Services();

            try
            {
                service1.OpenConnection();

                try
                {
                    //System.Diagnostics.Debug.Print("Ciao");
                    DataSet vds = new DataSet();
                    string sql = string.Format("SELECT Id_user,Message,Date FROM [Post] WHERE (Id_user = '" + id + "') and (SocialNetwork = 'Facebook') ORDER BY Date DESC");
                    SqlCommand vCom = new SqlCommand(sql, service1.conn);
                    SqlDataAdapter vda = new SqlDataAdapter(vCom);
                    vda.Fill(vds);
                    string message_user = vds.Tables[0].Rows[0]["Message"].ToString();
                    string date_user = vds.Tables[0].Rows[0]["Date"].ToString();

                    vda.Dispose();

                    string accessToken = services.ReadToken(id, "Facebook");


                    try
                    {
                        var Testclient = new FacebookClient(accessToken);

                    }
                    catch (FacebookOAuthException ex)
                    {
                        accessToken = RefreshAccessToken(accessToken);

                    }
                    //retry

                    var client = new FacebookClient(accessToken);

                    //checking if access token is still valid
                    //     var code = 

                    dynamic id_me = client.Get("me");
                    string id_fb = id_me.id;

                    dynamic me = client.Get("me/feed?limit=10");
                    string[] message = new string[10];
                    string[] date = new string[10];
                    string[] image_post = new string[10];
                    int[] likes = new int[10];
                    int[] comments = new int[10];
                    int count = 0;
                    char[] split = { 'T' };
                    char[] split2 = { '+' };
                    string date_now;
                    int flag = 0;
                    int flag2 = 0;


                    while (flag == 0)
                    {

                        for (int i = 0; i < 10; i++)
                        {
                            try
                            {
                                if ((me.data[i].message != null) && (me.data[i].from.id == id_fb))
                                {
                                    string[] data = me.data[i].updated_time.ToString().Split(split);
                                    string date_fb = data[0];
                                    string[] time_err = data[1].Split(split2);
                                    string time = time_err[0];

                                    date_now = Convert.ToDateTime(date_fb + " " + time).ToString();

                                    string a = HttpUtility.HtmlEncode(me.data[i].message.ToString());
                                    if ((HttpUtility.HtmlEncode(me.data[i].message.ToString()) == message_user) && (date_now == date_user))
                                    {
                                        i = 11;
                                        flag = 1;
                                        flag2 = 1;
                                    }
                                    else
                                    {
                                        message[count] = me.data[i].message.ToString();
                                        date[count] = date_fb + " " + time;



                                        if (me.data[i].likes != null)
                                        {
                                            foreach (var name in me.data[i].likes.data)
                                                likes[count]++;

                                        }


                                        if (me.data[i].comments != null)
                                        {
                                            foreach (var name in me.data[i].comments.data)
                                                comments[count]++;


                                        }






                                        DateTime aa = Convert.ToDateTime(date[count]);
                                        aa = aa.AddHours(2);
                                        date[count] = aa.ToString();
                                        System.Diagnostics.Debug.Print("time: " + date[count]);
                                        try
                                        {
                                            if (me.data[i].picture != null)
                                            {
                                                image_post[count] = me.data[i].picture.ToString();
                                            }
                                            else
                                            {
                                                image_post[count] = null;
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            System.Console.WriteLine(ex.Message);
                                            image_post[count] = null;
                                        }
                                        count++;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                System.Console.WriteLine(ex.Message);
                            }
                        }
                        if (flag2 != 1)
                        {
                            try
                            {
                                System.Diagnostics.Debug.Print("Paging");
                                string paging = me.paging.next.ToString();
                                char[] split3 = { '?' };

                                string[] next_page = paging.Split(split3);
                                me = client.Get(id_fb + "/feed?" + next_page[1]);
                            }
                            catch (Exception ex)
                            {
                                System.Console.WriteLine(ex.Message);
                                flag = 1;
                                System.Diagnostics.Debug.Print("Catch Paging");
                            }
                        }
                    }

                    for (int i = 0; i < count; i++)
                    {
                        string sql2 = string.Format("INSERT INTO [Post](Id_user,Message,Date,Picture,SocialNetwork,N_Likes,N_Comments,N_Shares) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')", id, HttpUtility.HtmlEncode(message[i]), date[i], image_post[i], "Facebook", likes[i], comments[i], 0);
                        System.Diagnostics.Debug.Print(sql2);
                        SqlCommand com2 = new SqlCommand(sql2, service1.conn);
                        com2.ExecuteNonQuery();

                    }

                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.Message);
                    System.Diagnostics.Debug.Print("Chiamo FB prime");
                    Boolean ris = MyPostsPrimeFB(id);
                }
                service1.CloseConnection();
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                System.Diagnostics.Debug.Print("Errore in FB");
                service1.CloseConnection();
                return false;
            }
        }

        private Boolean MyPostsPrimeFB(string id)
        {
            ServiceRest service1 = new ServiceRest();
            Services services = new Services();
            try
            {
                service1.OpenConnection();
                string accessToken = services.ReadToken(id, "Facebook");
                //System.Diagnostics.Debug.Print("A");
                var client = new FacebookClient(accessToken);
                dynamic id_me = client.Get("me");
                string id_fb = id_me.id;
                //System.Diagnostics.Debug.Print("Ciao: "+id_fb);
                dynamic me = client.Get("/me/feed?limit=50");
                //   dynamic me = client.Get ("me/feed?fields=message,from,picture,comments,likes&limit=50");
                //System.Diagnostics.Debug.Print("B"); 

                char[] split = { 'T' };
                char[] split2 = { '+' };
                int flag = 0;
                int temp = 0;
                string image_post = null;
                while (flag == 0)
                {
                    for (int i = 0; i < 50; i++)
                    {
                        try
                        {
                            if ((me.data[i].message != null) && (me.data[i].from.id == id_fb))
                            {
                                string[] data = me.data[i].updated_time.ToString().Split(split);
                                string date = data[0];

                                string[] time_err = data[1].Split(split2);
                                string time = time_err[0];

                                DateTime aa = Convert.ToDateTime(date + " " + time);
                                aa.AddHours(2);
                                date = aa.ToString();
                                System.Diagnostics.Debug.Print("time: " + date);



                                int comments = 0;

                                int likes = 0;


                                if (me.data[i].likes != null)
                                {
                                    foreach (var name in me.data[i].likes.data)
                                        likes++;

                                }


                                if (me.data[i].comments != null)
                                {
                                    foreach (var name in me.data[i].comments.data)
                                        comments++;

                                }



                                try
                                {
                                    if (me.data[i].picture != null)
                                    {
                                        image_post = me.data[i].picture.ToString();
                                    }
                                    else
                                    {
                                        image_post = null;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    System.Console.WriteLine(ex.Message);
                                    image_post = null;
                                }

                                string sql2 = string.Format("INSERT INTO [Post](Id_user,Message,Date,Picture,SocialNetwork,N_Likes,N_Comments,N_Shares) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')", id, HttpUtility.HtmlEncode(me.data[i].message.ToString()), date, image_post, "Facebook", likes, comments, 0);
                                System.Diagnostics.Debug.Print(sql2);
                                SqlCommand com2 = new SqlCommand(sql2, service1.conn);
                                com2.ExecuteNonQuery();
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Console.WriteLine(ex.Message);
                        }
                    }
                    if (temp < 4)
                    {
                        try
                        {
                            string paging = me.paging.next.ToString();
                            char[] split3 = { '?' };

                            string[] next_page = paging.Split(split3);
                            me = client.Get(id_fb + "/feed?" + next_page[1]);
                            temp++;
                        }
                        catch (Exception ex)
                        {
                            System.Console.WriteLine(ex.Message);
                            flag = 1;
                        }
                    }
                    else
                    {
                        flag = 1;
                    }
                }
                service1.CloseConnection();
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                System.Diagnostics.Debug.Print("Errore FB prime");
                service1.CloseConnection();
                return false;
            }
        }

        public Boolean MyTagsFB(string id)
        {
            ServiceRest service1 = new ServiceRest();
            Services services = new Services();

            try
            {
                service1.OpenConnection();

                try
                {
                    //System.Diagnostics.Debug.Print("Ciao");
                    DataSet vds = new DataSet();
                    string sql = string.Format("SELECT Id_user,Tag,Message,Date FROM [TagPost] WHERE (Id_user = '" + id + "') and (SocialNetwork = 'Facebook') ORDER BY Date DESC");
                    SqlCommand vCom = new SqlCommand(sql, service1.conn);
                    SqlDataAdapter vda = new SqlDataAdapter(vCom);
                    vda.Fill(vds);
                    string tag_user = vds.Tables[0].Rows[0]["Tag"].ToString();
                    string message_user = vds.Tables[0].Rows[0]["Message"].ToString();
                    string date_user = vds.Tables[0].Rows[0]["Date"].ToString();
                    //System.Diagnostics.Debug.Print("1: " + message_user);
                    vda.Dispose();

                    string accessToken = services.ReadToken(id, "Facebook");
                    var client = new FacebookClient(accessToken);
                    dynamic id_me = client.Get("me");
                    string id_fb = id_me.id;
                    //System.Diagnostics.Debug.Print("A: " + id_fb);
                    dynamic me = client.Get(id_fb + "/tagged?fields=message,created_time,from,picture");

                    string[] tag = new string[100];
                    string[] img_tag = new string[100];
                    string[] message = new string[100];
                    string[] date = new string[100];
                    string[] image_post = new string[100];
                    int count = 0;
                    char[] split = { 'T' };
                    char[] split2 = { '+' };
                    string date_now;
                    int flag = 0;
                    int flag2 = 0;

                    while (flag == 0)
                    {
                        for (int i = 0; i < 4; i++)
                        {
                            try
                            {
                                if ((me.data[i].message != null))
                                {
                                    string a = me.data[i].message.ToString();
                                    string id_from = me.data[i].from.id.ToString();
                                    dynamic from = client.Get(id_from + "?fields=picture");
                                    string img_from = from.picture.data.url.ToString();
                                    string[] data = me.data[i].created_time.ToString().Split(split);
                                    string date_fb = data[0];
                                    string[] time_err = data[1].Split(split2);
                                    string time = time_err[0];

                                    date_now = Convert.ToDateTime(date_fb + " " + time).ToString();

                                    if ((HttpUtility.HtmlEncode(me.data[i].message.ToString()) == message_user) && (date_now == date_user))
                                    {
                                        i = 11;
                                        flag = 1;
                                        flag2 = 1;
                                    }
                                    else
                                    {
                                        tag[count] = me.data[i].from.name.ToString();
                                        img_tag[count] = img_from;
                                        message[count] = me.data[i].message.ToString();

                                        date[count] = date_fb + " " + time;
                                        DateTime aa = Convert.ToDateTime(date[count]);
                                        aa = aa.AddHours(2);
                                        date[count] = aa.ToString();
                                        System.Diagnostics.Debug.Print("time: " + date[count]);


                                        try
                                        {
                                            if (me.data[i].picture != null)
                                            {
                                                image_post[count] = me.data[i].picture.ToString();
                                            }
                                            else
                                            {
                                                image_post[count] = null;
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            System.Console.WriteLine(ex.Message);
                                            image_post[count] = null;
                                        }
                                        count++;
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                System.Console.WriteLine(ex.Message);
                            }
                        }
                        if (flag2 != 1)
                        {
                            try
                            {
                                System.Diagnostics.Debug.Print("Paging");
                                string paging = me.paging.next.ToString();
                                char[] split3 = { '?' };

                                string[] next_page = paging.Split(split3);
                                me = client.Get(id_fb + "/tagged?" + next_page[1]);
                            }
                            catch (Exception ex)
                            {
                                System.Console.WriteLine(ex.Message);
                                flag = 1;
                                System.Diagnostics.Debug.Print("Catch Paging");
                            }
                        }
                    }

                    for (int i = 0; i < count; i++)
                    {
                        string sql2 = string.Format("INSERT INTO [TagPost](Id_user,Tag,Message,Date,Picture,SocialNetwork,Img_Tag) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", id, tag[i], HttpUtility.HtmlEncode(message[i]), date[i], image_post[i], "Facebook", img_tag[i]);
                        SqlCommand com2 = new SqlCommand(sql2, service1.conn);
                        com2.ExecuteNonQuery();

                    }

                }
                catch (Exception ex)
                {
                    System.Console.WriteLine(ex.Message);
                    System.Diagnostics.Debug.Print("Chiamo FB prime");
                    Boolean ris = MyTagsPrimeFB(id);
                }
                service1.CloseConnection();
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                System.Diagnostics.Debug.Print("Errore in FB");
                service1.CloseConnection();
                return false;
            }
        }

        private Boolean MyTagsPrimeFB(string id)
        {
            ServiceRest service1 = new ServiceRest();
            Services services = new Services();
            try
            {
                service1.OpenConnection();
                string accessToken = services.ReadToken(id, "Facebook");
                var client = new FacebookClient(accessToken);
                dynamic id_me = client.Get("me");
                string id_fb = id_me.id;
                //System.Diagnostics.Debug.Print("A: " + id_fb);
                dynamic me = client.Get(id_fb + "/tagged?fields=message,created_time,from,picture&limit=4");
                int flag = 0;

                char[] split = { 'T' };
                char[] split2 = { '+' };
                string image_post = null;
                while (flag == 0)
                {
                    for (int i = 0; i < 4; i++)
                    {
                        try
                        {
                            if ((me.data[i].message != null))
                            {
                                string id_from = me.data[i].from.id.ToString();
                                dynamic from = client.Get(id_from + "?fields=picture");
                                string img_from = from.picture.data.url.ToString();

                                string[] data = me.data[i].created_time.ToString().Split(split);
                                string date = data[0];
                                string[] time_err = data[1].Split(split2);
                                string time = time_err[0];

                                //conv date
                                DateTime aa = Convert.ToDateTime(date + " " + time);
                                aa.AddHours(2);
                                date = aa.ToString();


                                try
                                {
                                    if (me.data[i].picture != null)
                                    {
                                        image_post = me.data[i].picture.ToString();
                                    }
                                    else
                                    {
                                        image_post = null;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    System.Console.WriteLine(ex.Message);
                                    image_post = null;
                                }

                                string sql2 = string.Format("INSERT INTO [TagPost](Id_user,Tag,Message,Date,Picture,SocialNetwork,Img_Tag) values('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", id, me.data[i].from.name.ToString(), HttpUtility.HtmlEncode(me.data[i].message.ToString()), date, image_post, "Facebook", img_from);
                                //System.Diagnostics.Debug.Print(sql2);
                                SqlCommand com2 = new SqlCommand(sql2, service1.conn);
                                com2.ExecuteNonQuery();
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Console.WriteLine(ex.Message);
                        }
                    }
                    try
                    {
                        string paging = me.paging.next.ToString();
                        char[] split3 = { '?' };

                        string[] next_page = paging.Split(split3);
                        me = client.Get(id_fb + "/tagged?" + next_page[1]);
                    }
                    catch (Exception ex)
                    {
                        System.Console.WriteLine(ex.Message);
                        flag = 1;
                    }
                }
                service1.CloseConnection();
                return true;

            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                System.Diagnostics.Debug.Print("Errore FB prime");
                service1.CloseConnection();
                return false;
            }
        }
        public Boolean CrossPostingFB(string id, string message)
        {
            ServiceRest service1 = new ServiceRest();
            Services services = new Services();
            try
            {
                service1.OpenConnection();
                string accessToken = services.ReadToken(id, "Facebook");
                var client = new FacebookClient(accessToken);
                dynamic parameters = new ExpandoObject();
                parameters.message = message;
                parameters.link = "";
                parameters.picture = "";
                parameters.name = "";
                parameters.caption = "";
                parameters.description = "";
                dynamic result = client.Post("me/feed", parameters);

                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return false;
            }
        }
    }
    public static class Util
    {

        public static T FromJson<T>(this string s)
        {
            var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
            return ser.Deserialize<T>(s);
        }

        public static int countLikes(dynamic s)
        {
            List<dynamic> likeList = s.FromJson<List<dynamic>>();
            return likeList.Count;
        }
    }
}
